package com.zrrd.gmall.order.recevier;

import com.rabbitmq.client.Channel;
import com.zrrd.gmall.model.enums.ProcessStatus;
import com.zrrd.gmall.model.order.OrderInfo;
import com.zrrd.gmall.order.service.OrderService;
import com.zrrd.gmall.rabbit.constant.MqConstant;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class OrderRecevier {
    @Autowired
    private OrderService orderService;

    //监听消息
    @RabbitListener(queues = MqConstant.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId, Message message, Channel channel) throws IOException {
        System.out.println("收到延迟消息===>"+orderId);
        //如果收到的订单ID不为空
        if (orderId != null){
            //根据订单ID 查询订单对象
            OrderInfo orderInfo = orderService.getById(orderId);
            //如果该订单存在 并且 状态为未支付
            if (orderInfo != null && "UNPAID".equals(orderInfo.getOrderStatus())){
                //调用业务层更新订单状态和进度 为已关闭
                orderService.updateOrderStatus(orderId, ProcessStatus.CLOSED);
            }
        }

        //消息消费确认回执
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
